home *** CD-ROM | disk | FTP | other *** search
- Path: castle.nando.net!news
- From: actuary@nando.net (Bill McCarthy)
- Newsgroups: comp.lang.c
- Subject: Re: more problems with qsort
- Date: 3 Mar 1996 21:19:41 GMT
- Organization: Nando.net Public Access
- Message-ID: <4hd2dd$82q@castle.nando.net>
- References: <177399702S86.JW1675A@american.edu> <4h0j9e$ng5@clarknet.clark.net> <4h8bud$1vd@castle.nando.net> <825783387snz@genesis.demon.co.uk>
- Reply-To: actuary@nando.net (Bill McCarthy)
- NNTP-Posting-Host: grail1506.nando.net
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <825783387snz@genesis.demon.co.uk>, Lawrence Kirby <fred@genesis.demon.co.uk> writes:
- >In article <4h8bud$1vd@castle.nando.net>
- > actuary@nando.net "Bill McCarthy" writes:
- >
- >>In <4h0j9e$ng5@clarknet.clark.net>,
- >>yom@clark.net (yom) writes:
- >>
- >>>Since you're trying to sort a char**, the qsort function call must
- >>>look like this:
- >>>
- >>>qsort(array,lines,sizeof(char **),(int (*)(void *,void *)) compare);
- >>>
- >>>And your compare function must be defined like this:
- >>>
- >>>int compare(char **a,char **b) {return strcmp(*a,*b);}
- >>
- >>Didn't you mean to type "sizeof( char * )" which, IMHO, could be
- >>better expressed as "sizeof array[0]" ? Also, there's no need to
- >>further complicate the call of qsort with the cast on compare if
- >>you define compare() as:
- >
- >The code as written requires a diagnostic from the compiler (if stdlib.h
- >is included) because the comparison function type takes const void * arguments
- >and int (*)(void *, void *) is incompatible with
- >int (*)(const void *, const void *).
- >
- >Even if the cast is fixed the code results in undefined behaviour since
- >an int (char **, char **) function can't be legally called as an
- >int (const void *, const void *) function which is how qsort() will call it.
-
- OK Lawrence, but you are replying to me. I made two points:
-
- (1) the "sizeof(char **)" should be replaced with "sizeof(char *)"
- (2) the cast in front of compare can be eliminated by rewriting compare
-
- Which point did you disagree with?
-
- >>int compare( const void *a, const void *b )
- >>{
- >> return strcmp( *(const char **)a, *(const char **)b );
- >>}
- >
- >IMHO it is desirable to maintain corresponding consts where possible when
- >casting so better would be:
- >
- > return strcmp( *(char *const *)a, *(char *const *)b );
- >
- >or
- >
- > return strcmp( *(const char *const *)a, *(const char *const *)b );
-
- Thanks for catching my typo. Your second alternative is the one
- I've been using.
-
- Bill McCarthy
- actuary@nando.net
- Wendell, NC USA
-
-